#
# This is an obsolete twisted client
# LOOK AT client.py
#
import sys
from json import dumps, loads
from twisted.internet import reactor, defer
from twisted.web.client import  HTTPClientFactory, HTTPPageGetter

def doPost(url, data, headers = {}, followRedirect=False):
    factory = HTTPClientFactory(url=url, method='POST', postdata=data,
               headers=headers, followRedirect=followRedirect)
    reactor.connectTCP(factory.host, factory.port, factory)
    return factory

def print_error(reason, post):
    print 'Error: received status: %s, %s' % (post.status, post.message)
    print 'Reason: %s' % reason
    return reason


def print_ok(result, post):
    print 'OK: received status: %s, %s' % (post.status, post.message)
    print 'Result: %s' % result
    return result

def stop(_):
    reactor.stop()

def main(request_id, a, b):
    try:
        data = dumps({
            'server_name': 'Prova',
            'method_name': 'prod',
            'callback_url': 'http://localhost:8081/reply/%s' % request_id,
            'arguments': [a, b, 'http://localhost:8081/reply/progress_%s' % request_id],
            })
    except Exception, e:
        print 'Json error: %s' % str(e)
        return
    post = doPost('http://localhost:8080/updates/ciccio', data)
    post.deferred.addCallbacks(print_ok, print_error,[post], None, [post], None) 
    post.deferred.addCallbacks(stop, stop)

if __name__=='__main__':
    reactor.callWhenRunning(main, sys.argv[1], *sys.argv[2:])
    reactor.run()
